package com.atguigu.utils;

import io.minio.MinioClient;
import io.minio.PutObjectOptions;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

@Data
@Configuration
@EnableConfigurationProperties(MinioProperties.class)
public class MinioUploader {
    //执行有先后顺序
    @Autowired
    private MinioProperties minioProperties;
    @Autowired
    private MinioClient minioClient;

    @Bean
    MinioClient minioClient() throws Exception{
        MinioClient minioClient = new MinioClient(
                minioProperties.getEndpoint(),
                minioProperties.getAccessKey(),
                minioProperties.getSecretKey());
        boolean isExist = minioClient.bucketExists(minioProperties.getBucketName());
        if(!isExist){
            minioClient.makeBucket(minioProperties.getBucketName());
        }
        return minioClient;
    }

    public String uploadFile(MultipartFile file) throws Exception {
        //文件名称
        String fileName=file.getOriginalFilename();
        InputStream inputStream = file.getInputStream();
        PutObjectOptions options = new PutObjectOptions(inputStream.available(), -1);
        options.setContentType(file.getContentType());
        minioClient.putObject(minioProperties.getBucketName(),fileName,inputStream,options);
        //请求地址 endpoint+bucketname+objectname
        //http://121.89.208.247:9000/java0722/new.jpg
        //返回上传文件的路径
        String filePath=minioProperties.getEndpoint()+"/"+minioProperties.getBucketName()+"/"+fileName;
        return filePath;
    }
}
